const config = require('../common/config');
const {tokenPrivateKey, notTokenUrls} = config;

const jwt = require('jsonwebtoken');

const verifyToken = async (ctx, next) => {

  if (notTokenUrls.indexOf(ctx.url) !== -1) {
    await next();
    return;
  }
  // 从header中取出token
  const token = ctx.request.header['authorization'];
  if (!token) {
    ctx.body = {
      code: -1, msg: 'token不存在'
    };
    return
  }
  await jwt.verify(token, tokenPrivateKey, async (err, decoded) => {
    if (err) {
      const errType = err.name;
      if (errType === 'TokenExpiredError') {
        ctx.body = {code: config.tokenExpiredCode, msg: 'token已过期'};
      } else if (errType === 'JsonWebTokenError') {
        ctx.body = {code: config.tokenErrCode, msg: '无效的token'};
      } else {
        ctx.body = {code: -1, msg: 'token验证失败'};
      }
    } else {
      await next();
    }
  });
};

module.exports = verifyToken;
